package cn.learn.login;

import cn.learn.base.BaseController;
import cn.learn.domain.module.Module;
import cn.learn.domain.system.user.User;
import cn.learn.domain.system.wxuser.WxUser;
import cn.learn.service.module.ModuleService;
import cn.learn.service.system.user.UserService;
import cn.learn.service.system.wxuser.WxUserService;
import cn.learn.utils.commons.UtilFuns;
import com.alibaba.fastjson.JSONArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {
    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private UserService userService;

    /*shiro的登陆认证*/
    @RequestMapping("/login")
    public String login(String email, String password) {

//        System.out.println(wxUser);
        try {
            //1 获取subject对象
            Subject subject = SecurityUtils.getSubject();
            //2 创建一个token对象存账号和密码
            UsernamePasswordToken uptoken = new UsernamePasswordToken(email, password);
            //3 通过subject对象开启登陆入口（底层找安全管理器指向的reamls）
            subject.login(uptoken);
            //4 问shiro要认证好的用户
            User user = (User)subject.getPrincipal();
            // 将登陆用户存入session到页面展示
            session.setAttribute("user", user);
            // 权限--判断当前登陆用户的不同级别做不用的菜单数据查询
            List<Module> MenusList = userService.findMenus(user);
            //将用户的信息进行展示
            String openid = user.getOpenid();
            WxUser wxUser= wxUserService.findUserByOpenId(openid);

            session.setAttribute("wxUser",wxUser);
            // 将查询到的用户权限菜单带到页面展示
            session.setAttribute("modules", MenusList);
            //只有成功了才到项目的主体页面
        }catch (Exception e){
            request.setAttribute("error","用户名或者密码错误...");
            return "forward:/login.jsp";
        }

        //只有成功了才到项目的主体页面
        return "home/main";
    }

    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
//        SecurityUtils.getSubject().logout();   //登出
        session.removeAttribute("wxUser");
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
        return "home/home";
    }
}
